<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">
  <meta name="baidu-site-verification" content="code-ia4sE56m4l">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/all.min.css">
  
  <link rel="stylesheet" href="/blog/lib/animate-css/animate.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"tangmonk-meat.gitee.io","root":"/blog/","scheme":"Muse","version":"8.0.0-rc.4","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":"valine","storage":true,"lazyload":true,"nav":null,"activeClass":"valine"},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"path":"search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>

  <meta name="description" content="1 前言1.1 内嵌servlet 容器的情况下根据SpringBoot的启动原理，可以知道，是通过以下代码可以直接，启动SpringBoot应用(就是SpringApplication.run(...)方法)： 12345678@SpringBootApplicationpublic class SpringBootApplicationStarter &amp;#123;    public stat">
<meta property="og:type" content="article">
<meta property="og:title" content="外置Servlet容器启动SpringBoot应用的原理">
<meta property="og:url" content="https://tangmonk-meat.gitee.io/blog/2021/03/19/%E5%A4%96%E7%BD%AEServlet%E5%AE%B9%E5%99%A8%E5%90%AF%E5%8A%A8SpringBoot%E5%BA%94%E7%94%A8%E7%9A%84%E5%8E%9F%E7%90%86/index.html">
<meta property="og:site_name" content="唐僧肉BLOG">
<meta property="og:description" content="1 前言1.1 内嵌servlet 容器的情况下根据SpringBoot的启动原理，可以知道，是通过以下代码可以直接，启动SpringBoot应用(就是SpringApplication.run(...)方法)： 12345678@SpringBootApplicationpublic class SpringBootApplicationStarter &amp;#123;    public stat">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://s1.ax1x.com/2020/08/05/aD4F1O.png">
<meta property="og:image" content="https://s1.ax1x.com/2020/08/05/aD5dZd.png">
<meta property="og:image" content="https://s1.ax1x.com/2020/08/05/aDIM6S.png">
<meta property="article:published_time" content="2021-03-19T13:16:54.846Z">
<meta property="article:modified_time" content="2020-09-23T02:29:25.209Z">
<meta property="article:author" content="TANGMONK-MEAT">
<meta property="article:tag" content="java">
<meta property="article:tag" content="源码">
<meta property="article:tag" content="spring">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://s1.ax1x.com/2020/08/05/aD4F1O.png">

<link rel="canonical" href="https://tangmonk-meat.gitee.io/blog/2021/03/19/%E5%A4%96%E7%BD%AEServlet%E5%AE%B9%E5%99%A8%E5%90%AF%E5%8A%A8SpringBoot%E5%BA%94%E7%94%A8%E7%9A%84%E5%8E%9F%E7%90%86/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>外置Servlet容器启动SpringBoot应用的原理 | 唐僧肉BLOG</title>
  






  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <main class="main">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader">
        <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">唐僧肉BLOG</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">记录生活中的点点滴滴</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">44</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">17</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">38</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <section class="post-toc-wrap sidebar-panel">
          <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-%E5%89%8D%E8%A8%80"><span class="nav-number">1.</span> <span class="nav-text">1 前言</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-1-%E5%86%85%E5%B5%8Cservlet-%E5%AE%B9%E5%99%A8%E7%9A%84%E6%83%85%E5%86%B5%E4%B8%8B"><span class="nav-number">1.1.</span> <span class="nav-text">1.1 内嵌servlet 容器的情况下</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-2-%E5%9C%A8%E5%A4%96%E7%BD%AEservlet%E5%AE%B9%E5%99%A8%E7%9A%84%E6%83%85%E5%86%B5%E4%B8%8B"><span class="nav-number">1.2.</span> <span class="nav-text">1.2 在外置servlet容器的情况下</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-1-%E5%90%AF%E5%8A%A8%E6%B5%81%E7%A8%8B%EF%BC%88%E4%BB%A5Tomcat%E4%B8%BA%E4%BE%8B%EF%BC%89"><span class="nav-number">1.2.1.</span> <span class="nav-text">1.2.1 启动流程（以Tomcat为例）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-2-ServletContainerInitializer-%E6%8E%A5%E5%8F%A3"><span class="nav-number">1.2.2.</span> <span class="nav-text">1.2.2 ServletContainerInitializer 接口</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-%E5%A4%96%E7%BD%AETomcat%E5%90%AF%E5%8A%A8SpringBoot%E7%9A%84%E6%B5%81%E7%A8%8B%E5%8E%9F%E7%90%86"><span class="nav-number">2.</span> <span class="nav-text">2 外置Tomcat启动SpringBoot的流程原理</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#2-1-Tomcat-%E5%90%AF%E5%8A%A8"><span class="nav-number">2.1.</span> <span class="nav-text">2.1 Tomcat 启动</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-2-%E6%A0%B9%E6%8D%AEServlet3-1%E8%A7%84%E8%8C%83%EF%BC%8C%E6%89%BE%E5%88%B0ServletContainerInitializer%E7%9A%84%E5%AE%9E%E7%8E%B0%EF%BC%8C%E8%BF%9B%E8%A1%8C%E5%AE%9E%E4%BE%8B%E5%8C%96"><span class="nav-number">2.2.</span> <span class="nav-text">2.2 根据Servlet3.1规范，找到ServletContainerInitializer的实现，进行实例化</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-3-SpringServletContainerInitializer-%E7%B1%BB"><span class="nav-number">2.3.</span> <span class="nav-text">2.3 SpringServletContainerInitializer 类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-4-WebApplicationInitializer-Web%E5%BA%94%E7%94%A8%E5%88%9D%E5%A7%8B%E5%8C%96%E5%99%A8"><span class="nav-number">2.4.</span> <span class="nav-text">2.4 WebApplicationInitializer(Web应用初始化器)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-5-%E5%88%9B%E5%BB%BA-SpringBootServletInitializer%E7%9A%84%E5%AE%9E%E4%BE%8B%EF%BC%8C%E8%B0%83%E7%94%A8-onStartup%E6%96%B9%E6%B3%95"><span class="nav-number">2.5.</span> <span class="nav-text">2.5 创建 SpringBootServletInitializer的实例，调用 onStartup方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-6-createRootApplicationContext-%E8%AF%A6%E7%BB%86%E6%B5%81%E7%A8%8B%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90"><span class="nav-number">2.6.</span> <span class="nav-text">2.6 createRootApplicationContext 详细流程源码分析</span></a></li></ol></li></ol></div>
      </section>
      <!--/noindex-->

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="TANGMONK-MEAT"
      src="https://s1.ax1x.com/2020/09/22/wOscW9.jpg">
  <p class="site-author-name" itemprop="name">TANGMONK-MEAT</p>
  <div class="site-description" itemprop="description">直到这一刻微笑着说话为止，我至少留下了一公升眼泪</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">38</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">17</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">44</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/TANGMONK-MEAT" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;TANGMONK-MEAT" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:2950371251@qq.com" title="E-Mail → mailto:2950371251@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://gitee.com/TANGMONK-MEAT" title="Gitee → https:&#x2F;&#x2F;gitee.com&#x2F;TANGMONK-MEAT" rel="noopener" target="_blank"><i class="iconfont icongitee-fill-round fa-fw"></i>Gitee</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://www.leancloud.cn/" title="LeanCloud → https:&#x2F;&#x2F;www.leancloud.cn" rel="noopener" target="_blank"><i class="iconfont iconCloudupload fa-fw"></i>LeanCloud</a>
      </span>
  </div>
  <div class="cc-license animated" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/zh-CN" class="cc-opacity" rel="noopener" target="_blank"><img src="/blog/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </section>
    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </header>

      
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/TANGMONK-MEAT" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>

<noscript>
  <div id="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


      <div class="main-inner">
        

        <div class="content post posts-expand">
          

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://tangmonk-meat.gitee.io/blog/2021/03/19/%E5%A4%96%E7%BD%AEServlet%E5%AE%B9%E5%99%A8%E5%90%AF%E5%8A%A8SpringBoot%E5%BA%94%E7%94%A8%E7%9A%84%E5%8E%9F%E7%90%86/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://s1.ax1x.com/2020/09/22/wOscW9.jpg">
      <meta itemprop="name" content="TANGMONK-MEAT">
      <meta itemprop="description" content="直到这一刻微笑着说话为止，我至少留下了一公升眼泪">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="唐僧肉BLOG">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          外置Servlet容器启动SpringBoot应用的原理
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-03-19 21:16:54" itemprop="dateCreated datePublished" datetime="2021-03-19T21:16:54+08:00">2021-03-19</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-09-23 10:29:25" itemprop="dateModified" datetime="2020-09-23T10:29:25+08:00">2020-09-23</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/SpringBoot/" itemprop="url" rel="index"><span itemprop="name">SpringBoot</span></a>
                </span>
            </span>

          
            <span id="/blog/2021/03/19/%E5%A4%96%E7%BD%AEServlet%E5%AE%B9%E5%99%A8%E5%90%AF%E5%8A%A8SpringBoot%E5%BA%94%E7%94%A8%E7%9A%84%E5%8E%9F%E7%90%86/" class="post-meta-item leancloud_visitors" data-flag-title="外置Servlet容器启动SpringBoot应用的原理" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/blog/2021/03/19/%E5%A4%96%E7%BD%AEServlet%E5%AE%B9%E5%99%A8%E5%90%AF%E5%8A%A8SpringBoot%E5%BA%94%E7%94%A8%E7%9A%84%E5%8E%9F%E7%90%86/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/blog/2021/03/19/%E5%A4%96%E7%BD%AEServlet%E5%AE%B9%E5%99%A8%E5%90%AF%E5%8A%A8SpringBoot%E5%BA%94%E7%94%A8%E7%9A%84%E5%8E%9F%E7%90%86/" itemprop="commentCount"></span>
    </a>
  </span>
  
  <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>11k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>10 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="1-前言"><a href="#1-前言" class="headerlink" title="1 前言"></a>1 前言</h1><h2 id="1-1-内嵌servlet-容器的情况下"><a href="#1-1-内嵌servlet-容器的情况下" class="headerlink" title="1.1 内嵌servlet 容器的情况下"></a>1.1 内嵌servlet 容器的情况下</h2><p>根据<a target="_blank" rel="noopener" href="https://www.jianshu.com/p/ef6f0c0de38f">SpringBoot的启动原理</a>，可以知道，是通过以下代码可以直接，启动SpringBoot应用(就是<code>SpringApplication.run(...)</code>方法)：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SpringBootApplication</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SpringBootApplicationStarter</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        SpringApplication.run(SpringBootApplicationStarter.class, args);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<a id="more"></a>

<h2 id="1-2-在外置servlet容器的情况下"><a href="#1-2-在外置servlet容器的情况下" class="headerlink" title="1.2 在外置servlet容器的情况下"></a>1.2 在外置servlet容器的情况下</h2><p>同上，同样是调用了<code>SpringApplication.run(...)</code>方法，不过需要先启动 服务器，再间接<strong>创建-&gt;初始化-&gt;启动</strong>SpringBoot应用，以下就是这种情况下的SpringBoot启动流程：</p>
<p>这种启动流程原理，是依赖<strong>Servlet3.1规范</strong>的(大致如下)：</p>
<ul>
<li><p>根据Servlet3.1规范，服务器启动（web应用启动）会创建当前web应用里面<strong>每一个jar包</strong>里面<code>ServletContainerInitializer</code>的实例。</p>
</li>
<li><p><code>ServletContainerInitializer</code>的实现放在jar包的<code>META-INF/services</code>文件夹下，有一个名为<code>javax.servlet.ServletContainerInitializer</code>的文件，<strong>内容就是<code>ServletContainerInitializer</code>的实现类的全类名</strong>。</p>
</li>
<li><p>在任何 <code>Servlet Listener</code> 的事件被触发之前，当应用正在启动时，<code>ServletContainerInitializer</code> 的 <code>onStartup</code> 方法将被调用。</p>
</li>
<li><p><code>ServletContainerInitializer</code> 实现上的<code>@handlesTypes</code>注解用于寻找感兴趣的类，要么是<code>@HandlesTypes</code>注解指定的类，要么是指定类的子类。</p>
</li>
</ul>
<h3 id="1-2-1-启动流程（以Tomcat为例）"><a href="#1-2-1-启动流程（以Tomcat为例）" class="headerlink" title="1.2.1 启动流程（以Tomcat为例）"></a>1.2.1 启动流程（以Tomcat为例）</h3><ul>
<li><p>Tomcat启动</p>
</li>
<li><p>根据Servlet3.1规范，找到 ServletContainerInitializer 的实现，进行实例化</p>
</li>
<li><p>创建 ServletContainerInitializer 实例</p>
</li>
<li><p>调用 ServletContainerInitializer 实例 （<code>SpringServletContainerInitializer</code>）的 onStartup 方法</p>
</li>
<li><p>SpringBoot 应用，就是在 onStartup 方法中启动的</p>
</li>
</ul>
<h3 id="1-2-2-ServletContainerInitializer-接口"><a href="#1-2-2-ServletContainerInitializer-接口" class="headerlink" title="1.2.2 ServletContainerInitializer 接口"></a>1.2.2 ServletContainerInitializer 接口</h3><blockquote>
<p><code>ServletContainerInitializer</code> 就是一个接口，只有一个待实现的方法<code>onStartup</code></p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// javax/servlet/ServletContainerInitializer.class</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">ServletContainerInitializer</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">onStartup</span><span class="params">(Set&lt;Class&lt;?&gt;&gt; var1, ServletContext var2)</span> <span class="keyword">throws</span> ServletException</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="2-外置Tomcat启动SpringBoot的流程原理"><a href="#2-外置Tomcat启动SpringBoot的流程原理" class="headerlink" title="2 外置Tomcat启动SpringBoot的流程原理"></a>2 外置Tomcat启动SpringBoot的流程原理</h1><h2 id="2-1-Tomcat-启动"><a href="#2-1-Tomcat-启动" class="headerlink" title="2.1 Tomcat 启动"></a>2.1 Tomcat 启动</h2><p><a target="_blank" rel="noopener" href="https://www.cnblogs.com/54chensongxia/p/13236745.html">Tomcat启动原理</a></p>
<p>重点看下 <code>StandardContext</code> 类的 <code>startInternal</code> 方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">startInternal</span><span class="params">()</span> <span class="keyword">throws</span> LifecycleException </span>&#123;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 略</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 调用 所有的 ServletContainerInitializer 的 onStartup 方法</span></span><br><span class="line">    <span class="keyword">for</span> (Map.Entry&lt;ServletContainerInitializer, Set&lt;Class&lt;?&gt;&gt;&gt; entry :</span><br><span class="line">        initializers.entrySet()) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            entry.getKey().onStartup(entry.getValue(),</span><br><span class="line">                    getServletContext());</span><br><span class="line">        &#125; <span class="keyword">catch</span> (ServletException e) &#123;</span><br><span class="line">            log.error(sm.getString(<span class="string">&quot;standardContext.sciFail&quot;</span>), e);</span><br><span class="line">            ok = <span class="keyword">false</span>;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 略</span></span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="2-2-根据Servlet3-1规范，找到ServletContainerInitializer的实现，进行实例化"><a href="#2-2-根据Servlet3-1规范，找到ServletContainerInitializer的实现，进行实例化" class="headerlink" title="2.2 根据Servlet3.1规范，找到ServletContainerInitializer的实现，进行实例化"></a>2.2 根据Servlet3.1规范，找到ServletContainerInitializer的实现，进行实例化</h2><p>SpringBoot 中的 <code>ServletContainerInitializer</code> 实现类位置在<strong>spring-web</strong>模块下 </p>
<p><img data-src="https://s1.ax1x.com/2020/08/05/aD4F1O.png" alt="aD4F1O.png"></p>
<p><code>javax.servlet.ServletContainerInitializer</code>文件内容：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">org.springframework.web.SpringServletContainerInitializer</span><br></pre></td></tr></table></figure>

<h2 id="2-3-SpringServletContainerInitializer-类"><a href="#2-3-SpringServletContainerInitializer-类" class="headerlink" title="2.3 SpringServletContainerInitializer 类"></a>2.3 SpringServletContainerInitializer 类</h2><blockquote>
<p>这个类实现了，ServletContainerInitializer 接口，重写了onStartup方法</p>
</blockquote>
<p><code>SpringServletContainerInitializer</code>将<code>@HandlesTypes(WebApplicationInitializer.class)</code></p>
<p>标注的所有这个类型( <code>WebApplicationInitializer</code> )的类都传入到<code>onStartup</code>方法的 Set集合，</p>
<p>为这些 <code>WebApplicationInitializer</code> 类型的类</p>
<p>创建实例 并遍历调用其 onStartup 方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// /org/springframework/web/SpringServletContainerInitializer.class</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//感兴趣的类为WebApplicationInitializer及其子类</span></span><br><span class="line"><span class="meta">@HandlesTypes(&#123;WebApplicationInitializer.class&#125;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SpringServletContainerInitializer</span> <span class="keyword">implements</span> <span class="title">ServletContainerInitializer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//先调用onStartup方法，会传入一系列webAppInitializerClasses</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onStartup</span><span class="params">(<span class="meta">@Nullable</span> Set&lt;Class&lt;?&gt;&gt; webAppInitializerClasses, ServletContext servletContext)</span> <span class="keyword">throws</span> ServletException </span>&#123;</span><br><span class="line">        <span class="comment">// 用于存放 感兴趣的类 的list 集合</span></span><br><span class="line">        List&lt;WebApplicationInitializer&gt; initializers = <span class="keyword">new</span> LinkedList();</span><br><span class="line">        </span><br><span class="line">        Iterator var4;</span><br><span class="line">        <span class="keyword">if</span> (webAppInitializerClasses != <span class="keyword">null</span>) &#123;</span><br><span class="line">            var4 = webAppInitializerClasses.iterator();</span><br><span class="line">            <span class="comment">// 遍历感兴趣的类</span></span><br><span class="line">            <span class="keyword">while</span>(var4.hasNext()) &#123;</span><br><span class="line">                Class&lt;?&gt; waiClass = (Class)var4.next();</span><br><span class="line">                <span class="comment">// 判断是不是接口，是不是抽象类，是不是该类型</span></span><br><span class="line">                <span class="keyword">if</span> (!waiClass.isInterface() &amp;&amp; !Modifier.isAbstract(waiClass.getModifiers()) &amp;&amp; WebApplicationInitializer.class.isAssignableFrom(waiClass)) &#123;</span><br><span class="line">                    <span class="keyword">try</span> &#123;</span><br><span class="line">                        <span class="comment">// 实例化每个WebApplicationInitializer并添加到initializers中</span></span><br><span class="line">                        initializers.add((WebApplicationInitializer)ReflectionUtils.accessibleConstructor(waiClass, <span class="keyword">new</span> Class[<span class="number">0</span>]).newInstance());</span><br><span class="line">                    &#125; <span class="keyword">catch</span> (Throwable var7) &#123;</span><br><span class="line">                        <span class="keyword">throw</span> <span class="keyword">new</span> ServletException(<span class="string">&quot;Failed to instantiate WebApplicationInitializer class&quot;</span>, var7);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (initializers.isEmpty()) &#123;</span><br><span class="line">            servletContext.log(<span class="string">&quot;No Spring WebApplicationInitializer types detected on classpath&quot;</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            servletContext.log(initializers.size() + <span class="string">&quot; Spring WebApplicationInitializers detected on classpath&quot;</span>);</span><br><span class="line">            AnnotationAwareOrderComparator.sort(initializers);</span><br><span class="line">            var4 = initializers.iterator();</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 依次调用 WebApplicationInitializer 的onStartup方法</span></span><br><span class="line">            <span class="keyword">while</span>(var4.hasNext()) &#123;</span><br><span class="line">                WebApplicationInitializer initializer = (WebApplicationInitializer)var4.next();</span><br><span class="line">                initializer.onStartup(servletContext);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img data-src="https://s1.ax1x.com/2020/08/05/aD5dZd.png" alt="aD5dZd.png"></p>
<p>在<code>SpringServletContainerInitializer</code>方法中又调用每一个<code>WebApplicationInitializer</code> 的<br><code>onStartup</code>方法。</p>
<p>即先调用SpringServletContainerInitializer实例的onStartup方法，在onStartup()方法内部又遍历每一个WebApplicationInitializer类型的实例，调用其onStartup()方法。</p>
<h2 id="2-4-WebApplicationInitializer-Web应用初始化器"><a href="#2-4-WebApplicationInitializer-Web应用初始化器" class="headerlink" title="2.4 WebApplicationInitializer(Web应用初始化器)"></a>2.4 WebApplicationInitializer(Web应用初始化器)</h2><p>在 Servlet 3.0+环境中提供的一个接口，以便编程式配置<code>ServletContext</code>而非传统的xml配置。</p>
<p>该接口的实例被<code>SpringServletContainerInitializer</code>自动检测(<code>@HandlesTypes(WebApplicationInitializer.class)</code>这种方式)。</p>
<p>而SpringServletContainerInitializer是Servlet 3.0+容器自动引导的。</p>
<p>通过WebApplicationInitializer，以往在xml中配置的<code>DispatcherServlet</code>、<code>Filter</code>等都可以通过代码注入。</p>
<p>你可以不用直接实现WebApplicationInitializer，而选择继承<code>AbstractDispatcherServletInitializer</code>。</p>
<p><img data-src="https://s1.ax1x.com/2020/08/05/aDIM6S.png" alt="aDIM6S.png"></p>
<p>可以看到，将会创建我们的com.springboot.template.ServletInitializer(继承自SpringBootServletInitializer)实例，并调用onStartup方法。</p>
<h2 id="2-5-创建-SpringBootServletInitializer的实例，调用-onStartup方法"><a href="#2-5-创建-SpringBootServletInitializer的实例，调用-onStartup方法" class="headerlink" title="2.5 创建 SpringBootServletInitializer的实例，调用 onStartup方法"></a>2.5 创建 SpringBootServletInitializer的实例，调用 onStartup方法</h2><blockquote>
<p>继承这个类的，就是作为SpringBoot的启动类</p>
</blockquote>
<p>我定义的SpringBoot 启动类，<code>com.springboot.template.ServletInitializer</code> 继承 自   SpringBootServletInitializer；</p>
<p>SpringBootServletInitializer 又实现了 <code>WebApplicationInitializer</code>接口，并重写了它的 onStartup 方法。</p>
<p>重点是 这个 <code>createRootApplicationContext(servletContext)</code></p>
<p>通过这个方法 开始 创建-&gt;启动 springboot应用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// org/springframework/boot/web/servlet/support/SpringBootServletInitializer.class</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">SpringBootServletInitializer</span> <span class="keyword">implements</span> <span class="title">WebApplicationInitializer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 略</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 创建WebApplicationContext  和 为容器添加监听</span></span><br><span class="line">    <span class="comment">// 重点是 createRootApplicationContext(servletContext);</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onStartup</span><span class="params">(ServletContext servletContext)</span> <span class="keyword">throws</span> ServletException </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.logger = LogFactory.getLog(<span class="keyword">this</span>.getClass());</span><br><span class="line">        <span class="comment">// 创建 WebApplicationContext </span></span><br><span class="line">        WebApplicationContext rootApplicationContext = <span class="keyword">this</span>.createRootApplicationContext(servletContext);</span><br><span class="line">        <span class="comment">// 如果根容器不为null</span></span><br><span class="line">        <span class="keyword">if</span> (rootApplicationContext != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">// 则添加监听</span></span><br><span class="line">            servletContext.addListener(<span class="keyword">new</span> SpringBootServletInitializer.SpringBootContextLoaderListener(rootApplicationContext, servletContext));</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">this</span>.logger.debug(<span class="string">&quot;No ContextLoaderListener registered, as createRootApplicationContext() did not return an application context&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 开始 创建-&gt;启动 springboot应用</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> WebApplicationContext <span class="title">createRootApplicationContext</span><span class="params">(ServletContext servletContext)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 创建 SpringApplicationBuilder --这一步很关键</span></span><br><span class="line">        SpringApplicationBuilder builder = <span class="keyword">this</span>.createSpringApplicationBuilder();</span><br><span class="line">        <span class="comment">// 设置SpringBoot应用主启动类</span></span><br><span class="line">        <span class="comment">// 这里为 com.springboot.template.ServletInitializer</span></span><br><span class="line">        builder.main(<span class="keyword">this</span>.getClass());</span><br><span class="line">        <span class="comment">// 从servletContext中获取</span></span><br><span class="line">        <span class="comment">// servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)作为parent。</span></span><br><span class="line">        <span class="comment">// 第一次获取肯定为null</span></span><br><span class="line">        ApplicationContext parent = <span class="keyword">this</span>.getExistingRootWebApplicationContext(servletContext);</span><br><span class="line">        <span class="keyword">if</span> (parent != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">this</span>.logger.info(<span class="string">&quot;Root context already created (using as parent).&quot;</span>);</span><br><span class="line">            <span class="comment">// 将ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE重置为null</span></span><br><span class="line">            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, (Object)<span class="keyword">null</span>);</span><br><span class="line">            <span class="comment">// 注册一个新的ParentContextApplicationContextInitializer--包含parent</span></span><br><span class="line">            builder.initializers(<span class="keyword">new</span> ApplicationContextInitializer[]&#123;<span class="keyword">new</span> ParentContextApplicationContextInitializer(parent)&#125;);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 初始化 </span></span><br><span class="line">        <span class="comment">// 注册ServletContextApplicationContextInitializer--包含servletContext</span></span><br><span class="line">        builder.initializers(<span class="keyword">new</span> ApplicationContextInitializer[]&#123;<span class="keyword">new</span> ServletContextApplicationContextInitializer(servletContext)&#125;);</span><br><span class="line">        <span class="comment">// 设置applicationContextClass为AnnotationConfigServletWebServerApplicationContext</span></span><br><span class="line">        builder.contextClass(AnnotationConfigServletWebServerApplicationContext.class);</span><br><span class="line">        <span class="comment">// 调用configure方法，子类重写了这个方法，将SpringBoot的主程序类传入了进来</span></span><br><span class="line">        <span class="comment">// 此方法被启动引导类 ServletInitializer有方法重写， 传入的是应用构建器SpringApplicationBuilder， 也就是SpringBoot的主程序类</span></span><br><span class="line">        builder = <span class="keyword">this</span>.configure(builder);</span><br><span class="line">        <span class="comment">// 添加监听器</span></span><br><span class="line">        builder.listeners(<span class="keyword">new</span> ApplicationListener[]&#123;<span class="keyword">new</span> SpringBootServletInitializer.WebEnvironmentPropertySourceInitializer(servletContext)&#125;);</span><br><span class="line">        <span class="comment">// 返回一个准备好的SpringApplication ，准备run-很关键</span></span><br><span class="line">        SpringApplication application = builder.build();</span><br><span class="line">        <span class="keyword">if</span> (application.getAllSources().isEmpty() &amp;&amp; MergedAnnotations.from(<span class="keyword">this</span>.getClass(), SearchStrategy.TYPE_HIERARCHY).isPresent(Configuration.class)) &#123;</span><br><span class="line">            application.addPrimarySources(Collections.singleton(<span class="keyword">this</span>.getClass()));</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        Assert.state(!application.getAllSources().isEmpty(), <span class="string">&quot;No SpringApplication sources have been defined. Either override the configure method or add an @Configuration annotation&quot;</span>);</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.registerErrorPageFilter) &#123;</span><br><span class="line">            application.addPrimarySources(Collections.singleton(ErrorPageFilterConfiguration.class));</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        application.setRegisterShutdownHook(<span class="keyword">false</span>);</span><br><span class="line">        <span class="comment">// 启动SpringBoot应用</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.run(application);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 略</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="2-6-createRootApplicationContext-详细流程源码分析"><a href="#2-6-createRootApplicationContext-详细流程源码分析" class="headerlink" title="2.6 createRootApplicationContext 详细流程源码分析"></a>2.6 createRootApplicationContext 详细流程源码分析</h2><blockquote>
<p>/org/springframework/boot/web/servlet/support/SpringBootServletInitializer.class<br>的 <code>createRootApplicationContext</code> 的方法</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> WebApplicationContext <span class="title">createRootApplicationContext</span><span class="params">(ServletContext servletContext)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 创建 SpringApplicationBuilder --这一步很关键</span></span><br><span class="line">    SpringApplicationBuilder builder = <span class="keyword">this</span>.createSpringApplicationBuilder();</span><br><span class="line">    <span class="comment">// 略</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>跟踪代码到：</p>
<blockquote>
<p>/org/springframework/boot/builder/SpringApplicationBuilder.class</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">SpringApplicationBuilder</span><span class="params">(Class&lt;?&gt;... sources)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.application = createSpringApplication(sources);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>此时的Sources为空，继续跟踪代码：</p>
<blockquote>
<p>/org/springframework/boot/SpringApplication.class</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SpringApplication</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 略</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SpringApplication</span><span class="params">(Class&lt;?&gt;... primarySources)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>((ResourceLoader)<span class="keyword">null</span>, primarySources);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SpringApplication</span><span class="params">(ResourceLoader resourceLoader, Class&lt;?&gt;... primarySources)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.sources = <span class="keyword">new</span> LinkedHashSet();</span><br><span class="line">        <span class="keyword">this</span>.bannerMode = Mode.CONSOLE;</span><br><span class="line">        <span class="keyword">this</span>.logStartupInfo = <span class="keyword">true</span>;</span><br><span class="line">        <span class="keyword">this</span>.addCommandLineProperties = <span class="keyword">true</span>;</span><br><span class="line">        <span class="keyword">this</span>.addConversionService = <span class="keyword">true</span>;</span><br><span class="line">        <span class="keyword">this</span>.headless = <span class="keyword">true</span>;</span><br><span class="line">        <span class="keyword">this</span>.registerShutdownHook = <span class="keyword">true</span>;</span><br><span class="line">        <span class="keyword">this</span>.additionalProfiles = <span class="keyword">new</span> HashSet();</span><br><span class="line">        <span class="keyword">this</span>.isCustomEnvironment = <span class="keyword">false</span>;</span><br><span class="line">        <span class="keyword">this</span>.lazyInitialization = <span class="keyword">false</span>;</span><br><span class="line">        <span class="keyword">this</span>.resourceLoader = resourceLoader;</span><br><span class="line">        Assert.notNull(primarySources, <span class="string">&quot;PrimarySources must not be null&quot;</span>);</span><br><span class="line">        <span class="keyword">this</span>.primarySources = <span class="keyword">new</span> LinkedHashSet(Arrays.asList(primarySources));</span><br><span class="line">        <span class="comment">// web应用类型--Servlet</span></span><br><span class="line">        <span class="keyword">this</span>.webApplicationType = WebApplicationType.deduceFromClasspath();</span><br><span class="line">        <span class="comment">// 获取ApplicationContextInitializer，也是在这里开始首次加载spring.factories文件</span></span><br><span class="line">        <span class="keyword">this</span>.setInitializers(<span class="keyword">this</span>.getSpringFactoriesInstances(ApplicationContextInitializer.class));</span><br><span class="line">        <span class="comment">// 这里是第二次加载spring.factories文件</span></span><br><span class="line">        <span class="keyword">this</span>.setListeners(<span class="keyword">this</span>.getSpringFactoriesInstances(ApplicationListener.class));</span><br><span class="line">        <span class="keyword">this</span>.mainApplicationClass = <span class="keyword">this</span>.deduceMainApplicationClass();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 略</span></span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>ApplicationContextInitializer</code>(应用上下文初始化器)是spring组件<code>spring-context</code>组件中的一个接口，主要是spring ioc容器刷新之前的一个回调接口，用于处于自定义逻辑。</p>
<p>在ConfigurableApplicationContext<br>Spring IOC容器称为“已经被刷新”状态前的一个回调接口，去初始化ConfigurableApplicationContext。</p>
<p>通常用于需要对应用程序上下文进行某些编程初始化的Web应用程序中。</p>
<p>例如，与ConfigurableApplicationContext#getEnvironment() 对比，注册property sources或激活配置文件。</p>
<p>另外ApplicationContextInitializer(和子类)相关处理器实例被鼓励使用去检测org.springframework.core.Ordered接口是否被实现或是否存在org.springframework.core.annotation.Order注解，如果存在，则在调用之前对实例进行相应排序。</p>
<p><a target="_blank" rel="noopener" href="https://blog.csdn.net/J080624/article/details/80764031?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-6.edu_weight&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-6.edu_weight">参考</a></p>

    </div>

     <!-- 文章结束表示语-->
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
      
    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>TANGMONK-MEAT
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://tangmonk-meat.gitee.io/blog/2021/03/19/%E5%A4%96%E7%BD%AEServlet%E5%AE%B9%E5%99%A8%E5%90%AF%E5%8A%A8SpringBoot%E5%BA%94%E7%94%A8%E7%9A%84%E5%8E%9F%E7%90%86/" title="外置Servlet容器启动SpringBoot应用的原理">https://tangmonk-meat.gitee.io/blog/2021/03/19/外置Servlet容器启动SpringBoot应用的原理/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/zh-CN" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/java/" rel="tag"><i class="fa fa-tag"></i> java</a>
              <a href="/blog/tags/%E6%BA%90%E7%A0%81/" rel="tag"><i class="fa fa-tag"></i> 源码</a>
              <a href="/blog/tags/spring/" rel="tag"><i class="fa fa-tag"></i> spring</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2021/03/19/ubuntu20.04%E8%80%B3%E6%9C%BA%E6%B2%A1%E6%9C%89%E5%A3%B0%E9%9F%B3/" rel="prev" title="解决ubuntu20.04耳机没有声音">
      <i class="fa fa-chevron-left"></i> 解决ubuntu20.04耳机没有声音
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2021/03/19/%E6%90%AD%E5%BB%BA%20Hexo%20+%20gitee%20%E9%9D%99%E6%80%81%E5%8D%9A%E5%AE%A2%E7%BD%91%E7%AB%99/" rel="next" title="搭建 Hexo + gitee 静态博客网站">
      搭建 Hexo + gitee 静态博客网站 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



        </div>
        
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">TANGMONK-MEAT</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">148k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">2:15</span>
</div>

<!--
-->

<!--<div>
<span id="busuanzi_container_site_pv">
    本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span> 
 <span class="post-meta-divider">|</span> 
 <span class="post-meta-item-icon">
<span id="busuanzi_container_site_uv">
  本站访客数<span id="busuanzi_value_site_uv"></span>人次
</span>
</div> 

-->




        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/muse.js"></script>


<script src="/blog/js/next-boot.js"></script>


  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>




  
<script src="/blog/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments('#valine-comments', () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/valine@1/dist/Valine.min.js', () => {
    new Valine(Object.assign({
      el  : '#valine-comments',
      path: location.pathname,
    }, {"enable":true,"appId":"dkMV7sEQR97E6CWI5jduGKf3-gzGzoHsz","appKey":"JQfXJ0ELtfNma5bdMQk0vgwX","placeholder":"ヾﾉ≧∀≦)o来啊，快活啊!","avatar":"mm","meta":["nick","mail"],"pageSize":10,"language":"zh-cn","visitor":true,"comment_count":true,"recordIP":true,"serverURLs":null,"enableQQ":false,"requiredFields":[]}
    ));
  }, window.Valine);
});
</script>

</body>
</html>
